#!/usr/bin/env python
#!/usr/bin/env python
import sys
import antlr3
from parsing.GencfaLexer import GencfaLexer
from parsing.GencfaParser import GencfaParser
from graph.GenGraph import GenGraph
from graph.GenGraph import Genedge
    
def parse(file):
    stream = open(file)
    cStream = antlr3.StringStream(stream.read())
    lexer = GencfaLexer(cStream)
    tStream = antlr3.CommonTokenStream(lexer)
    parser = GencfaParser(tStream)
    parser.cfdg() #Execs first parser grammar rule
    
    symbol_table = {}
    "Sets a symbol table up with rule names and invocations."
    startshape = parser.sshape #gets startshape
    background = parser.bground #gets background params    
    names = parser.names #gets symbols list from GencfaParser.py
    
    count = 0
    cur_rule = ""
    for rule in names:
        if cur_rule == rule[-1]:
            count = count + 1               
        else:                 
            count = 1
            cur_rule = rule[-1]
        instance_name = rule[-1] + "#" + str(count) #instance name e.g. QUAD#3
        
        params = []
        for invoc in rule[:-1]:     #rule name is last on list. The rest are invocations.
            building = []
            for value in invoc[:-1]:
                building.append(tuple(value.split()))
            building.append(invoc[-1])
            params.append(building)
        
        symbol_table[instance_name] = params 
        print("SYMBOL: " + instance_name + " CONTAINS: " + str(symbol_table[instance_name]))
    
    grapho = GenGraph(file) #Creates graph object
    grapho.set_startshape(startshape)
    grapho.set_background(background)
    current_node = ""
    for instance_name in symbol_table.iterkeys():
        splited_instance = instance_name.split('#')
        node = splited_instance[0]
        if node != current_node:
            current_node = node.upper()   
        invocations = symbol_table[instance_name] 
        for invoc in invocations:
            edge = Genedge(invoc[:-1]) #creates edge object with adjustments as payload
            grapho.add_edge(current_node, invoc[-1], edge, splited_instance[1]) #origin, destination, payload, instance
        #end for
    #end for
    return grapho 
    
